/*
    Copyright (C) 2010-2011 AmigaVR
    
    This file is part of AmigaVR.
    Written by Laügt Franz <znarf94@gmail.com>

    AmigaVR is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AmigaVR is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AmigaVR.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "global.h"

void usart_init()
{
	UPORT.DIRCLR = PIN2_bm;
	UPORT.DIRSET = PIN3_bm;

	USART.CTRLC = USART_CHSIZE_8BIT_gc | USART_PMODE_DISABLED_gc;	// 8 bits, No parity, 1 Stop Bit (8N1)

	USART.BAUDCTRLA = (uint8_t) BSEL;
	USART.BAUDCTRLB = (uint8_t) (BSEL >> 8);

	USART.CTRLB |= USART_RXEN_bm | USART_TXEN_bm;	// enable Rx and Tx
}

void usart_close()
{
	USART.CTRLB &= ~USART_RXEN_bm | ~USART_TXEN_bm;    // enable Rx and Tx
}

uint8_t usart_recv_byte()
{
	while((USART.STATUS & USART_RXCIF_bm) == 0);	// wait until some data is received
	return USART.DATA;
}

void usart_send_byte(uint8_t byte)
{
	while((USART.STATUS & USART_DREIF_bm) == 0);
	USART.DATA = byte;
}

